#include "sys_config.h"

/**
 * @brief MQTT上传消息任务函数
 * @note 封装数据，上传信息
 * @param {*}
 * @return {*}
 */
void Mqtt_Send_Tack(void)
{
    // 组Topic
    char publish_topic[MQTT_TOPIC_LEN] = "";   
    char data[MQTT_DATA_MAX] = "";
 
    if (sprintf_s(publish_topic, MQTT_TOPIC_LEN, MQTT_TOPIC_PUB_PROPERTIES, DEVICE_ID) > 0) {
        while(1){
            // 组JSON数据
            memset_s(data, MQTT_DATA_MAX, 0, MQTT_DATA_MAX);
            printf("data = %s\n", data);
            Json_Enc_Data(data);
            // 发布消息
            MQTTClient_pub(publish_topic, data, strlen(data));
            sleep(MQTT_SEND_TASK_TIME);
        }
    }else
        printf("[error] Mqtt_Send_Tack\r\n");

}

/**
 * @brief 返回命令响应
 * @note {*}
 * @param {*}
 * @return {*}
 */
static void Send__Request(const char *request_id, int ret_code, int request_len)
{
    char *request_topic = (char *)malloc(strlen(MALLOC_MQTT_TOPIC_PUB_COMMANDS_REQ) +
                                            strlen(DEVICE_ID) + request_len + 1);
    char requst_data[100] = "";
    if (request_topic != NULL) {
        memset_s(request_topic,
                 strlen(DEVICE_ID) + strlen(MALLOC_MQTT_TOPIC_PUB_COMMANDS_REQ) + request_len + 1,
                 0,
                 strlen(DEVICE_ID) + strlen(MALLOC_MQTT_TOPIC_PUB_COMMANDS_REQ) + request_len + 1);
        if (sprintf_s(request_topic,
                      strlen(DEVICE_ID) + strlen(MALLOC_MQTT_TOPIC_PUB_COMMANDS_REQ) + request_len + 1,
                      MQTT_TOPIC_PUB_COMMANDS_REQ, DEVICE_ID, request_id) > 0) {
            sprintf(requst_data, "{\"result_code\": %d,\"response_name\": \"COMMAND_RESPONSE\",\"paras\": {\"result\": \"%s\"}}",
                        ret_code, ret_code?"error":"success");
            MQTTClient_pub(request_topic, requst_data, strlen(requst_data));
        }
        free(request_topic);
        request_topic = NULL;
    }
}

/**
 * @brief MQTT接收消息回调函数
 * @note 接收，解析，更新状态，回传响应
 * @param {*}
 * @return 0：成功，-1：失败
 */
int8_t mqttClient_sub_callback(unsigned char *topic, unsigned char *payload)
{
    if ((topic == NULL) || (payload == NULL)) {
        return -1;
    } else {
        printf("topic: %s\r\n", topic);
        printf("payload: %s\r\n", payload);

        // 提取出topic中的request_id
        char request_id[50] = {0};
        int ret_code = 1; // 1为失败
        if (0 == strcpy_s(request_id, sizeof(request_id),
                          topic + strlen(DEVICE_ID) + strlen("$oc/devices//sys/commands/request_id="))) {
            printf("request_id: %s\r\n", request_id);
            // 解析JSON数据
            ret_code = Json_Par_Data(payload);
            Send__Request(request_id, ret_code, sizeof(request_id));
        }
    }
    return 0;
}

/**
 * @brief MQTT接收消息任务
 * @note 接收到消息会自动调用回调函数mqttClient_sub_callback
 * @param {*}
 * @return {*}
 */
void Mqtt_Recv_Tack(void)
{
        while (1) {
        MQTTClient_sub();
        sleep(MQTT_RECV_TASK_TIME);
    }
}



